/*****实物设备*****/
<template><!---->
  <search-table
    :showPage="false"
    :columns="phyDevCol" 
    :data="phyDevData"
    @change-page="getTargetPage"
    @change-size="getTargetSize"
    >
  <Alert type="warning" show-icon slot="alert">
    <p style="color:#f90">注意事项:</p>
    <template v-if="configMode !== 1">
        <p>	1.第一步进行“一键申请”，一键申请会根据子网络个数自动生成对应的申请</p>
        <p>	2.第二步管理员在“运维系统”里的“物理资源”>“设备管理”>“虚实互联实物设备管理”进行审批</p>
        <p>	3.第三步在审批通过后，进行“一键绑定”</p>
        <p>	4.第四步绑定后的设备也可以“断开”和“恢复断开”，也可“绑定环境”切换到别的环境中去</p>
    </template>
    <template v-else>
      <p>	1.第一步管理员在“运维系统”里的“物理资源”>“设备管理”>“虚实互联实物设备管理”进行审批</p>
      <p>	2.第二步在审批通过后，进行“一键绑定”</p>
      <p>	3.第三步绑定后的设备也可以“断开”和“恢复断开”，也可“绑定环境”切换到别的环境中去</p>
    </template>  
  </Alert>
  <template slot="search">
    <Button  type='primary'  ghost @click="savePRApply" :disabled="disabledAllBtn || phyDevData.length > 0 || allPhyDevNodeList.length == 0" :loading="applyLoading" icon="md-add" style="margin-right:15px;" v-if="configMode !== 1">一键申请</Button>
    <Button  type='primary'  ghost @click="bindEnviron" :disabled="disabledAllBtn || disBindEnviron" :loading="batchBindEnvironLoading"  style="margin-right:15px;"><Icon type="md-settings" :size="16" class="position_i"/>一键绑定</Button>
  </template>
  <Modal v-model="PRApplyModal.show"
      :title="PRApplyModal.title"
      :loading = "PRApplyModal.loading"
      width="600px"
      :mask-closable = "false"
      @on-cancel="handleReset('formValidate')"
      @on-ok="savePRApply">

      <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="80" @submit.native.prevent="keydownEnter">
          <div v-if="formValidate.deviceNameListShow.length">
            <Tag v-for="(item,index) in formValidate.deviceNameListShow" closable @on-close="handleRemoveDevice(item)" :key="index">{{item}}</Tag>
          </div>
          <Row>
            <Col span="12">
              <Input type="text" v-model="deviceName" placeholder="请输入实物设备名称" :width="200" @keydown.enter.native="keydownEnter"/>
            </Col>
            <Col span="3" offset="2">
              <Button type="primary" long @click="handleAddDevice" icon="md-add">添加</Button>
            </Col>
          </Row>
      </Form>
    </Modal>
  <Modal
    v-model="isShowBindModal"
    title="绑定环境"
    :mask-closable=false
    :loading="bindModalLoading"
    @on-ok="saveBindPhyDevNode"
    ok-text="绑定"
    >
    <Row>
      <Col>
        <span>选择环境：</span><Select filterable v-model="selPhyDevNode" style="width:200px" filterable>
        <Option v-for="item in phyDevNodeList" :value="JSON.stringify(item)" :key="item.id" :title="item.networkName">{{item.networkName}}</Option>
      </Select>
        <!--<Button type="primary" style="margin-left:16px" @click="saveBindPhyDevNode">绑定</Button>-->
      </Col>
      <!--
      <h3 style="margin: 20px 0;font-size: 14px;">已绑定的实物设备节点</h3>
      <Table border :columns="bindPhyDevNodeCol" :data="bindPhyDevNodeList"></Table>
    -->
    </Row>
  </Modal>
  </search-table>
</template>

<script>
  import {queryPRApplyList,addPRApply,modifyPRApply,delPRApply,multiAddPRApply,
    getApplyPhyDevice,getPhyDevNodeList,bindPhyDevNode,getSubnetId,reconnectInput,breakInput,queryNetworkList} from '@/api/drill_compete'
  import {getstatusbyprjid} from '@/api/drill'
//import {queryCtfList} from '@/api/question'
//import {getFlagServerList} from '@/api/drill'
  import {getuserinstance} from '@/api/access_new'
	export default {
    name: 'scenes',
    props:['type','disabledAllBtn', 'configMode','isDistributed'],
    components:{},
	data(){
		const validateNum = (rule, value, callback) => { //验证只能填入数字
	      	var reg = new RegExp("^([1-9]|[1-9]\\d|100)$");
	      	//验证警戒值
	      	if(value){
	      		if (!reg.test(value)) {
	      			callback(new Error('请输入1-100的整数'));
	      		}else{
	      			callback()
	      		}
	      	}else{
	      		callback()
	      	}
	      }
	  	return {
        usedSubnetListNew:[],
            usedSubnetList: [], // 已经分配给团队的子网
	  	routeParams:{
          id:this.$route.query.id,
          prjid:this.$route.query.prjid
        },
        PRApplyModal:{
        	show:false,
        	title:'',
        	loading:true,
        	type:1 //1添加，2修改
        },
        pathList:[],
        applyId:'',//每个场景只能申请一次
        isShowBindModal:false,
        selPhyDevNode:'',
        loadingShowModal:false,
        phyDevNodeList:[],
        curPhyDevInfo:{},
        modifyStatue:false,
          deviceName:"",
//      isSaveDisabled:false,
//      showDisbaled:false,
//      isDisabled:false,
//      ishowTeam:true,
//      sencenMode:'',
//      sencenType:1,
//      selSenceName:'',
//      sencenList:[],
//      selSencenC:'',
//      sencenListC:[],
//      selSencen:'',
//      selSencenPrjId:'',
//      selSencenPrjIdC:'',
//      selSenceNameC:'',
//      searchPrjString: '',
//      PZ:10,
//      currentPage:1,
//      showFooter:true,
//      addSecens:false,
//      titleObj:{},
		accessGroupList:[],
        vmlists:[],
        teamlists:[],
		queryPRApplyInfo:{
			pageIndex:1,
			pageSize:10,
      sceneId:this.$route.query.id,
		},
        questionList:[],
        access:'1',
        bindPhyDevNodeCol:[
          {
            title:'名称',
            key:'name',
            align:'center',
            ellipsis:true,
            tooltip:true,
//          width:100
          },
          {
            title:'网络',
            key:'networkName',
            align:'center',
            ellipsis:true,
            tooltip:true,
            width:100
          },
          {
            title:'实物设备',
            key:'physicalName',
            align:'center',
            ellipsis:true,
            tooltip:true,
            width:100
          },
          {
            title:'状态',
            align:'center',
            ellipsis:true,
            tooltip:true,
            render:(h,params) => {
              return h('span',{},this.showPortIp(params.row.address))
            }
          },
        ],
        formValidate: {
//		  "createTime": "",
//		  "creator": "",
		  "description": "",
		  "deviceNameListShow": [
            // {
            //   value: '',
            //   index: 1,
            //   status: 1
            // }
          ],
		  "id": "",
		  "name": "",
		  "deviceName":"",
		  "projectId": this.$route.query.prjid,
		  "sceneId": this.$route.query.id,
		  "status": 0
        },
        oldFormValidate:{},
        ruleValidate: {
          name: [
            { required: true, message: '名字不能为空', trigger: 'change' }
          ],
          // deviceName: [
          //   { required: true, message: '设备名字不能为空', trigger: 'change' }
          // ],
          description: [
            { required: true, message: '请输入描述信息', trigger: 'change' }
          ],
          // deviceNameList: [
          //   { required: true,type:'array',min:1,message: '请填写设备名称', trigger: 'change' },
          // ]
        },
        initTargetObjData:{
          "createtime": "",
          "createuser": localStorage.getItem('username'),
          "frequency": 0,
          "id": "",
          "isshow": 1,
          "lastupdatetime": "",
          "modifier": "",
          "sceneid": "",
          "targetdes": "",
          "targetname": "",
          "targetsubmittype":0,
          "targettype": 0,
          "teamid": "",
          "type": 0,
          "uri": "",
          "vmid": "",
          "score":'0'
        },
        querytime:{},
        PRApplyCol:[
//        {
//          type: 'index',
//          align: 'center',
//          ellipsis:true,
////          width:60
//        },
          {
            title:'名称',
            key:'name',
            align:'center',
            ellipsis:true,
            tooltip:true,
            placement:'top-left'
//          width:100
          },
          {
            title:'状态',
            key:'status',
            align:'center',
            ellipsis:true,
            tooltip:true,
            render:(h,params) => {
				return h('Tag',{
					props:{
					   color:params.row.status == 1 ? 'success' :'default',
					   type:"border"
					},
					on:{
	                    click:()=>{
	                      //this.showAddAndUpdate(params.row)
	                    }
	                }
				},params.row.status == 1 ? '已配置' : '未配置' )
			}
          },
          {
            title:'描述',
            key:'description',
            align:'center',
            ellipsis:true,
            tooltip:true,
          },
          {
            title:'操作',
            key:'os',
//          align:'center',
            ellipsis:true,
            width:200,
            action:true,
            render:(h,params)=>{
              return h('div',[
                // h('Button',{
                //   props:{
                //     type:'primary',
                //     size:'small'
                //   },
                //   style:{
                //     marginRight:'5px'
                //   },
                //   on:{
                //     click:()=>{
                //       //this.showAddAndUpdate(params.row)
                //     }
                //   }
                // },'绑定实物设备'),
                h('Button',{
                  props:{
                    type:'primary',
                    size:'small'
                  },
                  style:{
                    marginRight:'5px'
                  },
                  on:{
                    click:()=>{
                      this.showAddAndUpdate(params.row)
                    }
                  }
                },'修改'),
                h('Poptip', {
                  props: {
                    confirm: true,
                    'ok-text': "确定",
                    'cancel-text': "取消",
                    type: 'error',
                    size: 'large',
                    title: '你确定要删除吗?',
                    transfer:true
                  },
                  on: {
                    'on-ok': () => {
                      this.delPRApply(params.row.id)
                    }
                  }
                }, [
                  h('Button', {
                    props: {
                      type: 'error',
                      size: 'small'
                    },
                    style: {
                      marginRight: '5px'
                    },
                  }, '删除')
                ])
              ])
            }

          }
        ],
        PRApplyData:[],
        PRApplyTotal:0,
        TargetId:'',
        phyDevCol:[
          {
            title:'设备名称',
            key:'deviceName',
            align:'center',
            ellipsis:true,
            tooltip:true,
            placement:'top-left',
            width:240
          },
          {
            title:'Vlan',
            key:'vlanId',
            align:'center',
            placement:'top-left'
//          width:100
          },
          // {
          //   title:'节点名称',
          //   key:'nodeName',
          //   align:'center',
          //   ellipsis:true,
          //   tooltip:true,
//          render:(h,params) => {
//            return h('span',{},params.row.nodeName?params.row.nodeName:'-')
//          },
          //   width:100
          // },
          {
            title:'环境名称',
            key:'netkworkName',
            align:'center',
            ellipsis:true,
            tooltip:true,
            width:100
//          render:(h,params) => {
//            return h('span',{},params.row.netkworkName?params.row.netkworkName:'-')
//          }
//          width:100
          },
          // 不需要展示IP
          // {
          //   title:'IP地址',
          //   align:'center',
          //   ellipsis:true,
          //   width:112,
          //   render:(h,params) => {
          //     return h('span',{},params.row.addresses?this.showPortIp(params.row.addresses):'-')
          //   }
          // },
          {
            title:'CIDR',
            key:'CIDR',
            align:'center',
            ellipsis:true,
            tooltip:true,
            width:100,
            render:(h,params) => {
              return h('span','192.168.20.0/24')
            }
          },
          {
            title:'网关',
            align:'center',
            key:'wg',
            ellipsis:true,
            tooltip:true,
            width:100,
            render:(h,params) => {
              return h('span','192.168.20.1')
            }
          },
          {
            title:'交换机名称',
            key:'swichName',
            align:'center',
            ellipsis:true,
            tooltip:true,
            width:100
          },
          {
            title:'交换机端口',
            align:'center',
            key:'swichPortName',
            ellipsis:true,
            tooltip:true,
            width:60
          },
          {
            title:'状态',
            key:'status',
            align:'center',
            ellipsis:true,
            tooltip:true,
            placement:'top-right',
            render:(h,params) => {
               return h('span', this.statusFilter(params.row.status))
            }
          },
          {
            title:'进度',
            key:'progress',
            align:'center',
            width:100,
            render: (h, params) => {
              return h('span', this.progressFilter(params.row.progress))
            }
          },
          {
            title:'申请时间',
            key:'createTime',
            align:'center',
            ellipsis:true,
            tooltip:true,
          },
          {
            title:'操作',
            key:'action',
//          align:'center',
            ellipsis:true,
            width:260,
            placement:'top-right',
            opList:[
              {
                txt:'绑定环境',
                fun:this.bindPhyDev,
                disabled:(data) => {
                  return !(data.progress==1) || this.disabledAllBtn
                }
              },
              {
                txt:'断开接入',
                fun:this.breakInput,
                disabled:(data) => {
                  return !(data.status==1) || this.disabledAllBtn || data.breakInputLoading
                },
                title: '你确定要断开接入吗?',
                tooltip:true
              },
              {
                txt:'恢复接入',
                fun:this.breakInput,
                disabled:(data) => {
                  return !(data.status==2) || this.disabledAllBtn || data.reconnectInputLoading
                },
                title: '你确定要恢复接入吗?',
                tooltip:true
              }
            ]
          }
        ],
        phyDevData:[],
        bindPhyDevNodeList:[],
        deviceIndex:1,
        exitNames:[],
        allPhyDevNodeList:[],
        //按钮loading控制
        applyLoading:false,
        batchBindEnvironLoading:false,
        breakInputLoading:false,
        reconnectInputLoading:false,
        bindModalLoading:false
	  	}
	},
	filters:{

	},
	computed:{
		disBindEnviron(){
			let phyData = this.phyDevData.filter(phyDev => {
    		let environ = this.phyDevNodeList.filter(node => phyDev.deviceName.indexOf(node.networkName) != -1);
    		return phyDev.progress == 1 && !phyDev.netkworkName && environ.length > 0;
      })
			return phyData.length == 0;
		}
	},
	mounted(){
    	//this.getAllSence()
    	//this.getAllTargetHost();
    	//this.getAccessGroupList();
    	//this.getAllVmlist();
    	//this.queryCtfQuestionList();
    	this.getPRApplyList();
    	this.getApplyPhyDevice();
    	this.getProjectInfo();
    	this.getPhyDevNodeList();
	},
    methods:{
    	initData(){
    		this.formValidate = {
	          "createTime": "",
			  "creator": "",
			  "description": "",
			  "deviceNameListShow": [
                  // {
                  //   value: '',
                  //   index: 1,
                  //   status: 1
                  // }
              ],
			  "id": "",
			  "name": "",
			  "projectId": this.$route.query.prjid,
			  "sceneId": this.$route.query.id,
			  "status": 0
	        }
    	},
      //输入是否重名
      checkIsSameName(rule, value, callback){
        if (this.exitNames.includes(value)) {
          if(this.exitNames.length===this.formValidate.deviceNameListShow.length){
            callback();
          }else{
            callback(new Error('请输入不同的设备名称'));
          }
        } else{
          callback();
          this.exitNames.push(value);
        }
      },
      bindPhyDev(bindPhyDev){
        this.selPhyDevNode = ''
    	  this.curPhyDevInfo = bindPhyDev;
    	  this.isShowBindModal = true;
    	  this.getPhyDevNodeList();

      },
      //增加删除实物设备
      handleRemoveDevice(item){
        //this.formValidate.deviceNameListShow[index].status = 0;
        //let name = this.formValidate.deviceNameListShow[index].value;
        let index = this.formValidate.deviceNameListShow.findIndex(i=>i===item);
        this.formValidate.deviceNameListShow.splice(index,1)
      },
      handleAddDevice(){
    	  if(this.formValidate.deviceNameListShow.includes(this.deviceName)){
    	    this.$Message.info('设备名称已存在，请重新输入');
    	    this.deviceName = '';
    	    return
          }
          this.formValidate.deviceNameListShow.push(this.deviceName);
          this.deviceName = '';
      },
      //绑定实物设备和实物节点
      saveBindPhyDevNode(type){
      	this.bindModalLoading = true;
      	return new Promise((resolve,reject) => {
    	  let _this = this;
    	  if(!this.selPhyDevNode){
    	  	this.$Message.warning('请先选择环境!');
    	  	this.bindModalLoading = false;
    	  	setTimeout(() => {
    	  		this.bindModalLoading = true;
    	  	},1000)
    	  	return
    	  }
    	  let selPhyDevNodeObj = JSON.parse(_this.selPhyDevNode);
       /* getSubnetId(_this.$route.query.prjId,selPhyDevNodeObj.networkId,selPhyDevNodeObj.id,{page:1,pageSize:999}).then(data=>{
          if(data.code===1){
            let subnetInfo = data.attribute.dataList[0];
            if(subnetInfo){
             let  subnetId = subnetInfo.id;
              bindPhyDevNode(this.curPhyDevInfo.taskId,subnetId,selPhyDevNodeObj.id).then(data=>{
                if(data.code===1){
                  this.$Message.info('绑定设备到实物节点成功!');
                  this.getPhyDevNodeList();
                  this.getPhyDevNodeList();
                }
              })
            }
          }
        })*/
        let dataObj={
          "networkId": selPhyDevNodeObj.networkId,
          "networkName": selPhyDevNodeObj.networkName,
          "nodeId": selPhyDevNodeObj.id,
          "nodeName": selPhyDevNodeObj.name
        }
        bindPhyDevNode(this.curPhyDevInfo.taskId,dataObj).then(data=>{
          if(data.code===1){
          	if(type != 'all'){
          		this.$Message.info('绑定设备到实物节点成功!');
          		this.getApplyPhyDevice();
          	}
          	this.isShowBindModal = false;
            resolve(1);
		//			this.reconnectInput(this.curPhyDevInfo.taskId,this.curPhyDevInfo.subnetId)
            // this.getPhyDevNodeList();
          }else{
          	if(type != 'all'){
          		this.$Message.info('绑定设备到实物节点失败!');
          	}
          	this.bindModalLoading = false;
          	setTimeout(() => {
	    	  		this.bindModalLoading = true;
	    	  	},1000)
          	resolve(0);
          }
        }).catch(error => {
        	if(type != 'all'){
        		this.$Message.info('绑定设备到实物节点失败!');
        	}
        	this.bindModalLoading = false;
        	setTimeout(() => {
    	  		this.bindModalLoading = true;
    	  	},1000)
        	resolve(0);
        })
        })
      },
      // 判断地址是否可用
      addressAvailable(addresses) {
    	 if (Array.isArray(addresses) && addresses.length) {
    	     return true
         }
    	 if (typeof addresses === 'string' && addresses) {
    	     return true
         }
    	 if (addresses === undefined) {
    	     return true
         }
    	 return false
      },
      //查询topo下实物节点列表
      getPhyDevNodeList(resolve){
    	  let _this = this;
    	  let params = {
    	    page:1,
          pageSize:9999,
          projectId:this.$route.query.prjid,
          //projectId:'f71835050d2046e383775dc54425fe14',
          enableDeployed:false,
        }
        return getPhyDevNodeList(params).then(data=>{
          _this.bindPhyDevNodeList = [];
          _this.phyDevNodeList = [];
          if(data.code===1){
            let phyDevNodeList = data.data.list;
            this.allPhyDevNodeList = data.data.list;
            for(let i = 0;i<phyDevNodeList.length;i++){
              // addresses数据结构有变，为向前兼容，需要新增判断逻辑
              let addresses = phyDevNodeList[i].addresses
              if(this.addressAvailable(addresses)){
                _this.bindPhyDevNodeList.push(phyDevNodeList[i])
              }else{
                _this.phyDevNodeList.push(phyDevNodeList[i])
              }
            }
            this.phyDevNodeList.sort((a,b) => {
            	return Number(a.networkName.split('_')[1] || 0) - Number(b.networkName.split('_')[1] || 0)
            });
            if(resolve){
              resolve(_this.bindPhyDevNodeList)
            }
            // this.phyDevNodeList = phyDevNodeList.filter(item=>!item.address);
            // this.bindPhyDevNodeList = phyDevNodeList.filter(bind=>bind.address);
            //this.phyDevNodeList = data.data.list;
          }
        })
      },
      getApplyPhyDevice(){
        Promise.all([new Promise(resolve=>{
          getApplyPhyDevice(this.$route.query.id).then(data=>{
            if(data.code===1){
              //this.phyDevData = data.data.items || data.data;
              let datas = data.data.items  ||[]
              if(resolve){
                resolve(datas)
              }
            }
          })
        }),new Promise(resolve=>{
          this.getPhyDevNodeList(resolve)
        })]).then(data=>{
          this.phyDevData = data[0].map(item=>{
            let arr = {...item};
            data[1].forEach(bind=>{
              if(bind.id===item.nodeId){
                arr = {...item,...bind}
              }
            })
            return arr;
          })
        })
      },
    	showAddAndUpdate(info){
    		this.initData();
    		this.exitNames = [];
    		this.PRApplyModal.show = true;
    		this.modifyStatue = false;
    		if(!info){
    			this.PRApplyModal.title = '添加实物设备申请';
    			this.PRApplyModal.type = 1;
    			this.access = "1";
    		}else{
    			this.PRApplyModal.title = '修改实物设备申请';
    			this.PRApplyModal.type = 2;
    			this.modifyStatue = true;
    			//this.formValidate = {};
    			this.oldFormValidate = JSON.parse(JSON.stringify(info));
    			this.formValidate = JSON.parse(JSON.stringify(info));
    			// this.formValidate.path = info.targetTempInfos[0].info;
              // this.question = {imageId:this.formValidate.imageId};
    			this.setTeamGroup(this.formValidate.teamId);
    			//this.formValidate.externalPort = this.formValidate.externalPort;
    			//this.formValidate.port = this.formValidate.port;
    			// if(this.formValidate.externalPort || this.formValidate.externalIp ){
    			// 	this.access = "2";
    			// }else{
    			// 	this.access = "1";
    			// }
    		}
    	},
      //显示端口IP
      showPortIp(address){
    	  let str = '-';
    	  if(address&&address.length>0){
    	    str = address.map(addr=>addr.ipv4).join(',')
        }
    	  return str;
      },
	  	addPRApply(){
    	  //let deviceName = JSON.parse(JSON.stringify(this.formValidate)).deviceName.replace(/;/g,'；')
        if (this.usedSubnetList.length === 0) {
            this.$Message.warning('暂未查询到接入机器信息，无法申请')
            return
        }
        let requestApi = addPRApply;
	  	let params = {}
	  	if(this.applyId){
          requestApi = multiAddPRApply;
          params.id = this.applyId;
          params.data = this.usedSubnetListNew;
        }else{
          requestApi = addPRApply;
          params = JSON.parse(JSON.stringify(this.formValidate));
          params.deviceBeans=this.usedSubnetListNew
          params.deviceNameList = this.usedSubnetList;
          params.name = `${this.$route.query.name}竞赛申请实物设备`;
          params.description = `${this.$route.query.name}竞赛申请实物设备`;
        }
        requestApi(params).then(data => {
	  			if(data.code==1){
	  				this.getPRApplyList();
	  				this.getApplyPhyDevice();
	  				this.$Message.info('操作成功');
	  				this.handleReset('formValidate');
//	  				this.PRApplyModal.show = false;
	  			}else{
	  				this.cancelLoading('PRApplyModal');
	  			}
	  			this.applyLoading = false;
	  		}).catch(error => {
//	  			this.cancelLoading('PRApplyModal');
						this.applyLoading = false;
	  		})
	  	},
	  	modifyPRApply(){
	  		let params = JSON.parse(JSON.stringify(this.formValidate));
	  		let id = params.id;
	  		modifyPRApply(id,params).then(data => {
	  			if(data.code==1){
	  				this.getPRApplyList();
	  				this.$Message.info('操作成功');
	  				this.handleReset('formValidate');
	  				this.PRApplyModal.show = false;
	  			}else{
	  				this.cancelLoading('PRApplyModal');
	  				this.$Message.warning(data.message);
	  			}
	  		}).catch(error => {
	  			this.cancelLoading('PRApplyModal');
	  		})
	  	},
	  	savePRApply(){
	  		this.applyLoading = true;
    	  if(this.formValidate.deviceNameListShow.length){
            if(this.PRApplyModal.type == 1){
              this.addPRApply();
            }else{
              this.modifyPRApply();
              //this.$Message.warning(data.message);
            }
          }else{
            this.$Message.info('请输入实物设备名称!')
          }
	  	},
	  	getPRApplyList(){
	  		queryPRApplyList(this.queryPRApplyInfo).then(data => {
	  			if(data.code==1){
	  				this.PRApplyData = data.data.items || data.data;
	  			  if(this.PRApplyData[0]){
              this.applyId = this.PRApplyData[0].id;
            }
	  				this.PRApplyTotal = data.data.total;
	  			}else{

	  			}
	  		})
	  	},
	  	breakInput(phy){
	  		this.$set(phy,'breakInputLoading',true);
	  		breakInput(phy.taskId).then(data => {
	  			if(data.code==1){
	  			  this.$Message.info('断开接入成功');
	  				this.getPRApplyList();
            this.getApplyPhyDevice();
	  			}else{
						this.$Message.error(data.message);
	  			}
	  			this.$set(phy,'breakInputLoading',false);
	  		}).catch(error => {
	  			this.$set(phy,'breakInputLoading',false);
	  			this.$Message.error('断开接入失败');
	  		})
	  	},
      reconnectInput(phy){
      	this.$set(phy,'reconnectInputLoading',true);
        let params = {
        	id:phy.taskId,
        	subnetId:phy.subnetId
        }
	  		reconnectInput(params).then(data => {
	  			if(data.code==1){
	  			  this.$Message.info('恢复接入成功');
	  				this.getPRApplyList();
            this.getApplyPhyDevice();
	  			}else{
						this.$Message.error(data.message);
	  			}
	  			this.$set(phy,'reconnectInputLoading',false);
	  		}).catch(error => {
	  			this.$set(phy,'reconnectInputLoading',false);
	  			this.$Message.error('恢复接入失败');
	  		})
	  	},
	  	cancelLoading(name){
	    	this[name].loading = false;
	      	setTimeout(() => {
	      		this[name].loading = true;
	      	})
	    },
	    typeFilter(val){
	      let str = '';
	      switch (val) {
	      	case 0:str = 'Flag';break;
	        case 1:str = '多个虚拟机Flag相同';break;
	        case 2:str = '多个虚拟机Flag不同';break;
	        case 3:str = '文档';break
	        default:break;
	      }
	      return str;
	    },
	    getAllVmlist(partyId,imageId){
	        let params = {
				page:1,
				pageSize:10000,
				sortBy:'name',
				order:'asc',
				findPorts:true
			}
	    if(this.question){
	    	params.imageId = this.question.imageId;
	    }
	    if(this.group){
	    	params.party = this.group.partyId;
	    }
			queryVmWithParty(this.routeParams.prjid,params).then(data => {
				if(data.code == 1){
					this.vmlists = data.data.list || data.data;
					//this.getVmIp(this.formValidate.vmId);
					if(this.vmlists.length > 0){
						let server = this.vmlists.filter(vm => vm.id == this.formValidate.vmId)[0];
	    		        if(server){
	    		        	this.getFlagServerList(server.address[0].ips[0].ipAddress);
	    		        }
					}
				}
			})
	    },
	    getAccessGroupList(){
			if(!this.routeParams.id){
				return;
			}
			let params = {
				pageIndex:1,
				pageSize:2147483647,
				testId:this.routeParams.id
			};
			this.selectGroupList = [];
//			this.getPartyList();
			getaccessgrouplist(params).then(data => {
				if(data.code == 1){
					this.accessGroupList = data.data.items;
				}else if(data.code == -2) {
					this.accessGroupList = [];
				}else{
					this.$Message.warning(data.message);
				}
				//this.getUserTaskList();
			})
		},
	    getTargetSize(size){
	      this.queryPRApplyInfo.pageSize = size;
	      this.getPRApplyList()
	    },
	    getTargetPage(page){
	      this.queryPRApplyInfo.pageIndex = page;
	      this.getPRApplyList()
	    },
	    setTeamQuestion(val){
	    	if(!val){
	    		return
	    	}
	    	this.question = this.questionList.filter(question => question.chaId == val)[0];
	    	this.formValidate.port = this.question.port;
	    	//this.formValidate.vmId = '';
	    	this.getAllVmlist();
	    },
	    changeTeamGroup(val){
	    	this.formValidate.vmId = '';
	    	if(!val){
	    		return
	    	}
	    	this.setTeamGroup(val);
	    },
	    setTeamGroup(val){
	    	if(!val){
	    		return
	    	}
	    	this.group =  this.accessGroupList.filter(group => group.id == val)[0];
	    	this.formValidate.teamName = this.group.name;
	    	this.getAllVmlist();
	    },
	    handleReset (name) {
	      //this.$refs[name].resetFields();
	//    this.addTarget = false;
	        this.initData();
	        this.$refs [name].fields.forEach(function (e) {
			      if (e.fieldValue != undefined && e.fieldValue!='') {
			          e.resetField()
			      }
			})
	    },
	    queryCtfQuestionList(){//查询ctf题列表-不分页--不需要环境
	        let obj = {
	          pageIndex:1,
	          pageSize:2147483647,
	          isNeedEnv:'1',
	          visibility:'share',
	          //isNeedSubmitFlag:'1',
	          //category:this.autoPro.ctfType.join(',')
	        };
	        let _this = this;
	        queryCtfList(obj).then(data => {
	          if(data.code == 1){
	            _this.questionList = data.data.items.filter(ques => ques.imageId) || data.data;
	            if(_this.questionList.length == 0){
	            	_this.$Message.warning('该工程下没有满足要求的虚拟机');
	            }
	          }else{
	            _this.$Message.warning(data.message);
	          }
	        })
	    },
	    changeVm(id){
	    	this.formValidate.path = '';
	    	this.getVmIp(id);
	    },
	    getVmIp(id){
	    	if(id){
	    		let server = this.vmlists.filter(vm => vm.id == id)[0];
	    		this.getFlagServerList(server.address[0].ipv4);
	    	}
	    },
	    getFlagServerList(ip){
	    	let curIp = ip.split('.').slice(0,3).join('.');
	    	let params = {
	    		page:1,
	    		pageSize:1000,
	    		projectId:this.$route.query.prjid,
	    		ip:curIp
	    	}
	    	getFlagServerList(params).then(data => {
	    		if(data.code == 1){
	    			//this.pathList = data.data.list;
	    			this.formValidate.path = data.data.list[0].addresses[0].applyFlagUrl;
	    		}
	    	})
	    },
	    changeAccess(access){
//	    	if(access == "1" && this.PRApplyModal.type == 2){
//	    		this.formValidate.externalPort = this.oldFormValidate.externalPort;
//    			this.formValidate.externalIp = this.oldFormValidate.externalIp;
//	    	}else if(access == "2" && this.PRApplyModal.type == 2){
//	    		this.formValidate.port = this.oldFormValidate.port;
//	    	}
	    },
      progressFilter(val){
        let str='';
        switch(val){
          case 0:str = '申请中';break;
          case 1:str = '申请通过';break;
          case 2:str = '申请拒绝';break;
          default:str='申请拒绝';break;
        }
        return str;
      },
      statusFilter(val){
        let str='';
        switch(val){
          case 0:str = '未配置';break;
          case 1:str = '已配置，已连接';break;
          case 2:str = '已配置，已断开';break;
          default:str='未配置';break;
        }
        return str;
      },
      keydownEnter(){
      	return false;
      },
      getProjectInfo(){
			getstatusbyprjid(this.$route.query.prjid).then(data => {
				if(data.code == 1){
					this.projectInfo = data.attribute;
					this.getProjectSubnet();
				}
			})
		},
      getProjectSubnet(){
	    	queryNetworkList(this.$route.query.prjid,this.projectInfo.network.id).then(data => {
	    		if(data.code == 1){
	    			let subnetList = [];
	    			data.attribute.editorStage.childs.forEach(item => {
	    				subnetList = subnetList.concat(item.childs);
	    			})
	    			subnetList = subnetList.filter(subnet => subnet.dataType == 'NW');
	    			let sceneName = this.$route.query.name;
	    			subnetList.forEach(subnet => {
	    				this.formValidate.deviceNameListShow.push(`${this.$route.query.name}_${subnet.name}`);
	    			})
                    getuserinstance({
                        testId:this.$route.query.id,
                        pageIndex:1,
                        pageSize:2147483646
                    }).then(data => {
                        let projectGroupMemberList = []
                        if(data.code == 1){
                            projectGroupMemberList = data.data.items.filter(item => item.inviterName != '内部服务用户');
                        } else {
                            this.$Message.warning(data.message);
                        }
                        let pushId = []
                        projectGroupMemberList.forEach(vm => {
                            subnetList.forEach(subnet => {
                                if (Number(vm.partyId) === Number(subnet.party) && !pushId.includes(subnet.id)) {
                                    this.usedSubnetList.push(`${this.$route.query.name}_${subnet.name}`)
                                    if(this.isDistributed==1){
                                        let arr={
                                          deviceName:`${this.$route.query.name}_${subnet.name}`,
                                          rangeId:vm.rangeId,
                                        }
                                        this.usedSubnetListNew.push(arr)
                                    } else{
                                      let arr={
                                          deviceName:`${this.$route.query.name}_${subnet.name}`,
                                        }
                                       this.usedSubnetListNew.push(arr)
                                    }  
                                    pushId.push(subnet.id)
                                }
                            })
                        })
                        console.log(projectGroupMemberList,'projectGroupMemberListprojectGroupMemberList');
                        console.log(subnetList,'subnetListsubnetList');
                    })
	    		}
	    	})
	    },
	    bindEnviron(){
	    	this.batchBindEnvironLoading = true;
	    	let proArr = this.phyDevData.filter(phyDev => {
	    		let environ = this.phyDevNodeList.filter(node => phyDev.deviceName.indexOf(node.networkName) != -1);
	    		return phyDev.progress == 1 && !phyDev.netkworkName && environ.length > 0;
	    	}).map(phyDev => {
	    		let environ = this.phyDevNodeList.filter(node => phyDev.deviceName.indexOf(node.networkName) != -1);
	    		if(environ.length > 0){
	    			this.curPhyDevInfo = phyDev;
	    			this.selPhyDevNode = JSON.stringify(environ[0]);
	    			return this.saveBindPhyDevNode('all');
	    		}
	    	})
	    	if(proArr.length > 0){
	    		Promise.all(proArr).then(data => {
		    		if(data.some(item => item == 0)){
		    			this.$Message.error('绑定设备到实物节点失败!');
		    		}else{
		    			this.$Message.info('绑定设备到实物节点成功!');
		    		}
		    		this.batchBindEnvironLoading = false;
		    		this.getApplyPhyDevice();
		    	})
	    	}else{
	    		this.batchBindEnvironLoading = false;
	    		this.$Message.info('没有符合条件的信息!');
	    	}
	    }
  }
}
</script>

<style>
  .drillsTable .ivu-poptip-body {
    text-align: left!important;
  }
  .scenesHeader{
    margin-bottom: 16px;
  }
  .drillTables{
    min-height: 300px;
  }
  .drillsTable.ivu-table-wrapper{
    overflow: inherit;
  }
</style>
<style scoped>
  .Titles{
    background: #eeeeee;
    margin: 16px auto;
    padding: 10px 0;
  }
  .targetHeader{
    /*padding: 10px;*/
    margin: 15px 0;
  }
</style>
